<template>
  <div class="course-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>课程管理</h1>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="showAddModal = true">+ 添加课程</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="课程名称：">
          <el-input v-model="searchForm.name" placeholder="请输入课程名称" style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="课程学科：">
          <el-select v-model="searchForm.subject" placeholder="请选择" clearable style="width: 200px;">
            <el-option label="AI智能应用开发(Java)" :value="'1'"></el-option>
            <el-option label="AI大模型开发(Python)" :value="'2'"></el-option>
            <el-option label="AI鸿蒙开发" :value="'3'"></el-option>
            <el-option label="AI大数据" :value="'4'"></el-option>
            <el-option label="AI嵌入式" :value="'5'"></el-option>
            <el-option label="AI测试" :value="'6'"></el-option>
            <el-option label="AI运维" :value="'7'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用人群：">
          <el-select v-model="searchForm.target" placeholder="请选择" clearable style="width: 200px;">
            <el-option label="小白学员" :value="'1'"></el-option>
            <el-option label="初级程序员" :value="'2'"></el-option>
            <el-option label="中级程序员" :value="'3'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="courseList" style="width: 100%" border stripe height="50vh">
        <el-table-column prop="id" label="序号" width="80"></el-table-column>
        <el-table-column prop="subject" label="课程学科" width="180">
          <template #default="scope">
            {{ getSubjectName(scope.row.subject) }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="课程名称"></el-table-column>
        <el-table-column prop="price" label="价格（元）" width="100"></el-table-column>
        <el-table-column prop="target" label="适用人群" width="120">
          <template #default="scope">
            {{ getTargetName(scope.row.target) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="课程介绍">
          <template #default="scope">
            {{ scope.row.description || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editCourse(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="openDeleteModal(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加课程模态框 -->
    <el-dialog
      v-model="showAddModal"
      title="添加课程"
      width="600px"
      destroy-on-close
    >
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item label="课程学科" prop="subject">
          <el-select v-model="addForm.subject" placeholder="请选择学科" style="width: 100%;">
            <el-option label="AI智能应用开发(Java)" :value="'1'"></el-option>
            <el-option label="AI大模型开发(Python)" :value="'2'"></el-option>
            <el-option label="AI鸿蒙开发" :value="'3'"></el-option>
            <el-option label="AI大数据" :value="'4'"></el-option>
            <el-option label="AI嵌入式" :value="'5'"></el-option>
            <el-option label="AI测试" :value="'6'"></el-option>
            <el-option label="AI运维" :value="'7'"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入2-20字" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        
        <el-form-item label="适用人群" prop="target">
          <el-select v-model="addForm.target" placeholder="请选择适用人群" style="width: 100%;">
            <el-option label="小白学员" :value="'1'"></el-option>
            <el-option label="初级程序员" :value="'2'"></el-option>
            <el-option label="中级程序员" :value="'3'"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程价格（元）" prop="price">
          <el-input-number v-model="addForm.price" :min="1" :max="99999" :step="1" style="width: 100%;"></el-input-number>
        </el-form-item>
        
        <el-form-item label="课程介绍">
          <el-input type="textarea" v-model="addForm.description" :rows="3" maxlength="100" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddModal = false">取消</el-button>
          <el-button type="primary" @click="submitAddCourse">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑课程模态框 -->
    <el-dialog
      v-model="showEditModal"
      title="编辑课程"
      width="600px"
      destroy-on-close
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="课程学科" prop="subject">
          <el-select v-model="editForm.subject" placeholder="请选择学科" style="width: 100%;">
            <el-option label="AI智能应用开发(Java)" :value="'1'"></el-option>
            <el-option label="AI大模型开发(Python)" :value="'2'"></el-option>
            <el-option label="AI鸿蒙开发" :value="'3'"></el-option>
            <el-option label="AI大数据" :value="'4'"></el-option>
            <el-option label="AI嵌入式" :value="'5'"></el-option>
            <el-option label="AI测试" :value="'6'"></el-option>
            <el-option label="AI运维" :value="'7'"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入2-20字" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        
        <el-form-item label="适用人群" prop="target">
          <el-select v-model="editForm.target" placeholder="请选择适用人群" style="width: 100%;">
            <el-option label="小白学员" :value="'1'"></el-option>
            <el-option label="初级程序员" :value="'2'"></el-option>
            <el-option label="中级程序员" :value="'3'"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程价格（元）" prop="price">
          <el-input-number v-model="editForm.price" :min="1" :max="99999" :step="1" style="width: 100%;"></el-input-number>
        </el-form-item>
        
        <el-form-item label="课程介绍">
          <el-input type="textarea" v-model="editForm.description" :rows="3" maxlength="100" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEditModal = false">取消</el-button>
          <el-button type="primary" @click="submitEditCourse">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认模态框 -->
    <el-dialog
      v-model="showDeleteModal"
      title="确认删除"
      width="400px"
      destroy-on-close
    >
      <div class="delete-confirm-content">
        <p>确定要删除该课程吗？</p>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDeleteModal = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCourseList, createCourse, updateCourse, deleteCourse } from '../api/course'

export default {
  name: 'CourseView',
  data() {
    return {
      // 搜索表单
      // 数据映射
      subjectMap: {
        '1': 'AI智能应用开发(Java)',
        '2': 'AI大模型开发(Python)',
        '3': 'AI鸿蒙开发',
        '4': 'AI大数据',
        '5': 'AI嵌入式',
        '6': 'AI测试',
        '7': 'AI运维'
      },
      targetMap: {
        '1': '小白学员',
        '2': '初级程序员',
        '3': '中级程序员'
      },
      // 搜索表单
      searchForm: {
        name: '',
        subject: '',
        target: ''
      },
      // 分页数据
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      jumpPage: 1,
      // 课程列表
      courseList: [],
      // 模态框状态
      showAddModal: false,
      showEditModal: false,
      showDeleteModal: false,
      // 添加课程表单
      addForm: {
        subject: '',
        name: '',
        target: '',
        price: null,
        description: ''
      },
      // 编辑课程表单
      editForm: {
        id: '',
        subject: '',
        name: '',
        target: '',
        price: null,
        description: ''
      },
      // 删除课程信息
      deleteCourseId: '',
      // 表单验证规则
      addRules: {
        subject: [
          { required: true, message: '请选择课程学科', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 2, max: 20, message: '课程名称长度应为2-20字', trigger: 'blur' }
        ],
        target: [
          { required: true, message: '请选择适用人群', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入课程价格', trigger: 'blur' },
          { type: 'number', min: 1, max: 99999, message: '请输入1-99999之间的整数', trigger: 'blur' }
        ]
      },
      editRules: {
        subject: [
          { required: true, message: '请选择课程学科', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 2, max: 20, message: '课程名称长度应为2-20字', trigger: 'blur' }
        ],
        target: [
          { required: true, message: '请选择适用人群', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入课程价格', trigger: 'blur' },
          { type: 'number', min: 1, max: 99999, message: '请输入1-99999之间的整数', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 总页数
    totalPages() {
      return Math.ceil(this.totalCount / this.pageSize)
    },
    // 可见的页码
    visiblePages() {
      const totalPages = this.totalPages
      const currentPage = this.currentPage
      const pages = []
      
      if (totalPages <= 5) {
        for (let i = 1; i <= totalPages; i++) {
          pages.push(i)
        }
      } else {
        if (currentPage <= 3) {
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
        } else if (currentPage >= totalPages - 2) {
          for (let i = totalPages - 4; i <= totalPages; i++) {
            pages.push(i)
          }
        } else {
          for (let i = currentPage - 2; i <= currentPage + 2; i++) {
            pages.push(i)
          }
        }
      }
      
      return pages
    }
  },
  mounted() {
    // 加载课程列表数据
    this.loadCourseList()
  },
  methods: {
    // 获取学科名称
    getSubjectName(subjectId) {
      return this.subjectMap[subjectId] || '-';
    },

    // 获取目标学员名称
    getTargetName(targetId) {
      return this.targetMap[targetId] || '-';
    },

    // 加载课程列表
    async loadCourseList() {
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          name: this.searchForm.name,
          subject: this.searchForm.subject ? Number(this.searchForm.subject) : undefined,
          target: this.searchForm.target ? Number(this.searchForm.target) : undefined
        }
        
        const response = await getCourseList(params)
        
        if (response.code === 1) {
          this.courseList = response.data.rows || []
          this.totalCount = response.data.total || 0
        } else {
          this.$message.error(response.msg || '加载课程列表失败')
        }
      } catch (error) {
        this.$message.error('加载课程列表失败，请稍后重试')
      } finally {
        this.jumpPage = this.currentPage
      }
    },
    
    // 搜索
    search() {
      this.currentPage = 1
      this.loadCourseList()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        subject: '',
        target: ''
      }
      this.currentPage = 1
      this.loadCourseList()
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
    },
    
    // 跳转到指定页
    goToPage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page
        this.loadCourseList()
      }
    },
    
    // 上一页
    goToPrevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.loadCourseList()
      }
    },
    
    // 下一页
    goToNextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.loadCourseList()
      }
    },
    
    // 首页
    goToFirstPage() {
      if (this.currentPage > 1) {
        this.currentPage = 1
        this.loadCourseList()
      }
    },
    
    // 末页
    goToLastPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage = this.totalPages
        this.loadCourseList()
      }
    },
    
    // 跳页
    jumpToPage() {
      let page = parseInt(this.jumpPage)
      if (isNaN(page) || page < 1) page = 1
      if (page > this.totalPages) page = this.totalPages
      this.goToPage(page)
    },
    
    // 改变每页显示数量
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.loadCourseList()
    },
    
    // 改变当前页码
    handleCurrentChange(current) {
      this.currentPage = current
      this.loadCourseList()
    },
    
    // 编辑课程
    editCourse(course) {
      this.editForm = {
        id: course.id,
        subject: String(course.subject),
        name: course.name,
        target: String(course.target),
        price: course.price,
        description: course.description || ''
      }
      this.showEditModal = true
    },
    
    // 打开删除确认模态框
    openDeleteModal(id) {
      this.deleteCourseId = id
      this.showDeleteModal = true
    },
    
    // 提交添加课程
    async submitAddCourse() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const courseData = {
              subject: Number(this.addForm.subject),
              name: this.addForm.name,
              target: Number(this.addForm.target),
              price: Number(this.addForm.price),
              description: this.addForm.description
            }
            
            const response = await createCourse(courseData)
            
            if (response.code === 1) {
              this.showAddModal = false
              this.$refs.addFormRef.resetFields()
              this.$message.success('课程添加成功')
              this.loadCourseList()
            } else {
              this.$message.error(response.msg || '添加课程失败')
            }
          } catch (error) {
            this.$message.error('添加课程失败，请稍后重试')
          }
        }
      })
    },
    
    // 提交编辑课程
    async submitEditCourse() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const courseData = {
              id: this.editForm.id,
              subject: Number(this.editForm.subject),
              name: this.editForm.name,
              target: Number(this.editForm.target),
              price: Number(this.editForm.price),
              description: this.editForm.description
            }
            
            const response = await updateCourse(courseData)
            
            if (response.code === 1) {
              this.showEditModal = false
              this.$message.success('课程编辑成功')
              this.loadCourseList()
            } else {
              this.$message.error(response.msg || '编辑课程失败')
            }
          } catch (error) {
            this.$message.error('编辑课程失败，请稍后重试')
          }
        }
      })
    },
    
    // 确认删除
    async confirmDelete() {
      try {
        const response = await deleteCourse(this.deleteCourseId)
        
        if (response.code === 1) {
          this.showDeleteModal = false
          this.deleteCourseId = null
          this.$message.success('课程删除成功')
          this.loadCourseList()
        } else {
          this.$message.error(response.msg || '删除课程失败')
        }
      } catch (error) {
        this.$message.error('删除课程失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.course-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header h1 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 24px;
}

.action-buttons {
  margin-bottom: 20px;
  text-align: right;
}

.search-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-item label {
  font-size: 14px;
  color: #666;
  min-width: 80px;
}

.form-input,
.form-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  width: 200px;
}

.search-buttons {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.table-container {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  max-height: 50vh;
  overflow-y: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
  position: sticky;
  top: 0;
  z-index: 10;
}

.intro-cell {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-default {
  background-color: #6c757d;
  color: white;
}

.btn-default:hover {
  background-color: #545b62;
}

.btn-edit {
  background-color: #28a745;
  color: white;
  padding: 4px 12px;
  margin-right: 8px;
}

.btn-edit:hover {
  background-color: #218838;
}

.btn-delete {
  background-color: #dc3545;
  color: white;
  padding: 4px 12px;
}

.btn-delete:hover {
  background-color: #c82333;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #c82333;
}

.pagination-section {
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-info {
  font-size: 14px;
  color: #666;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background-color: #f8f9fa;
  border-color: #007bff;
}

.page-btn.active {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-jump {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.page-input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  text-align: center;
}

.page-size select {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.required {
  color: #dc3545;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #007bff;
}

.error-message {
  color: #dc3545;
  font-size: 12px;
  margin-top: 4px;
  display: block;
}

.char-count {
  display: block;
  text-align: right;
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-input,
  .form-select {
    width: 100%;
  }
  
  .search-buttons {
    margin-left: 0;
    justify-content: center;
  }
  
  .table-container {
    max-height: 40vh;
  }
  
  .data-table {
    font-size: 12px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px;
  }
  
  .btn-edit,
  .btn-delete {
    padding: 2px 8px;
    font-size: 12px;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
  
  .pagination-controls {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>